package com.woniu.order.service.impl;

import com.woniu.entity.Result;
import com.woniu.order.mapper.OrderMapper;
import com.woniu.order.pojo.Order;
import com.woniu.order.pojo.OrderItem;
import com.woniu.order.mapper.OrderItemMapper;
import com.woniu.order.service.IOrderItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.pay.entity.PayObject;
import com.woniu.pay.feign.AlipayFeignClient;
import com.woniu.product.feign.ProductFeignClient;
import com.woniu.product.pojo.Product;
import com.woniu.user.entity.feign.PickAddressFeignClient;
import com.woniu.user.entity.feign.UserInfoFeignClient;
import com.woniu.user.pojo.PickAddress;
import com.woniu.util.IdWorker;
import nonapi.io.github.classgraph.json.Id;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单中所包含的商品 服务实现类
 * </p>
 *
 * @author lydia
 * @since 2023-02-16
 */
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements IOrderItemService {

    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private PickAddressFeignClient pickAddressFeignClient;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AlipayFeignClient alipayFeignClient;

    @Override
    public void addProductToCart(String id, Integer productQuantity, String username) {
        //0.判断购物车里面有没有这个商品，存在的话，修改数据
        Object object = redisTemplate.boundHashOps("cart_" + username).get(id);
        if (object != null){
            OrderItem orderItem = (OrderItem) object;
            orderItem.setProductQuantity(orderItem.getProductQuantity() + productQuantity);
            redisTemplate.boundHashOps("cart_" + username).put(id,productQuantity);
            return;
        }
        //1.根据商品ID查询商品信息
        Result<Product> result = productFeignClient.selectProductById(id);
        //获取product数据
        Product product = result.getData();
        //2.封装信息到orderItem
        OrderItem orderItem = new OrderItem();
        orderItem.setProductId(id);
        orderItem.setProductCategoryId(product.getProductCategoryId());
        orderItem.setProductQuantity(productQuantity);
        orderItem.setProductPic(product.getProductPic());
        orderItem.setProductName(product.getProductName());
        orderItem.setProductPrice(product.getPrice());
        //3.返回数据,将orderItem保存到Redis里面去
        redisTemplate.boundHashOps("cart_" + username).put(id,orderItem);
    }

    @Override
    public List<OrderItem> displayProductFormCart(String username) {
        //1.通过用户名获取购物车数据
        List<OrderItem> cartList = redisTemplate.boundHashOps("cart_" + username).values();
        if (cartList.isEmpty()){
            return null;
        }
        return cartList;
    }

    @Override
    public void deleteProductToCart(String id, String username,Integer productQuantity) {
        //1.从Redis里面找到数据
        Object object = redisTemplate.boundHashOps("cart_" + username).get(id);
        if (object != null){
            OrderItem orderItem = (OrderItem) object;
            if (orderItem.getProductQuantity() > productQuantity){
                orderItem.setProductQuantity(orderItem.getProductQuantity() - productQuantity);
                redisTemplate.boundHashOps("cart_" + username).put(id,orderItem);
            }else {
                redisTemplate.boundHashOps("cart_" + username).delete(id);
            }
        }
    }

    @Override
    public List<OrderItem> listSelectCartItem(String[] ids, String username) {
        List<OrderItem> orderItemList = new ArrayList<>();
        // 1. 遍历ids数组，在购物车中获取对应的商品
        if(ids != null && ids.length > 0){
            for(String id : ids){
                OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps("cart_" + username).get(id);
                orderItemList.add(orderItem);
            }
        }
        return orderItemList;
    }

//    @Override
//    public String displayChooseProductsByUser(DisplayChooseProductByUserDTO displayChooseProductByUserDTO,String username) throws Exception {
//        BigDecimal total = new BigDecimal(0);
//        //1.判断商品库存
//        for (String id : displayChooseProductByUserDTO.getIds()) {
//            Product product = productFeignClient.selectProductById(id).getData();
//            OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps("cart_" + username).get(id);
//            if (product.getStock() < orderItem.getProductQuantity()){
//                throw new Exception("库存不够");
//            }
//            //计算总金额,total.add()累加，还需要赋值
//            total = total.add(orderItem.getProductPrice().multiply(new BigDecimal(orderItem.getProductQuantity())));
//        }
//        //2.查询收货地址
//        PickAddress pickAddress = pickAddressFeignClient.queryById(displayChooseProductByUserDTO.getReceiverId()).getData();
//        //3.创建并保存order对象
//        Order order = new Order();
//        IdWorker idWorker = new IdWorker(0,1);
//        long orderNo = idWorker.nextId();
//        //4.创建并保存orderItem对象
//        order.setNo(orderNo + "");//订单编号,雪花算法IDwork
//        order.setUserId(userInfoFeignClient.getByUsername(username).getData().getId());
//        order.setStatus(0);
//        order.setCreatedTime(new Date());
//        order.setUserName(username);
//        order.setTotalAmount(total);
//        order.setPayAmount(total);
//        order.setReceiverName(pickAddress.getReceiverName());
//        order.setReceiverCity(pickAddress.getReceiverCity());
//        order.setReceiverDetailAddress(pickAddress.getReceiverDetailAddress());
//        order.setReceiverPhone(pickAddress.getReceiverPhone());
//        order.setReceiverProvince(pickAddress.getReceiverProvince());
//        order.setReceiverPostCode(pickAddress.getReceiverPostCode());
//        order.setReceiverRegion(pickAddress.getReceiverRegion());
//        //保存到数据库
//        orderMapper.insert(order);
//        //创建并保存orderItem
//        for (String id : displayChooseProductByUserDTO.getIds()) {
//            OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps("cart_" + username).get(id);
//            orderItem.setOrderId(order.getId());
//            orderItem.setOrderNo(order.getNo());
//            //保存到数据库
//            orderItemMapper.insert(orderItem);
//            //5.删除对应的购物车中的商品,添加完后删除
//            //redisTemplate.boundHashOps("cart_" + username).delete(id);
//        }
//        //6.预扣库存,调用product微服务
//        for (String id : displayChooseProductByUserDTO.getIds()) {
//            Product product = productFeignClient.selectProductById(id).getData();
//            OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps("cart_" + username).get(id);
//            assert orderItem != null;
//            productFeignClient.updateStock(id,orderItem.getProductQuantity());
//        }
//        for (String id : displayChooseProductByUserDTO.getIds()) {
//            OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps("cart_" + username).get(id);
//            orderItem.setOrderId(order.getId());
//            orderItem.setOrderNo(order.getNo());
//            //保存到数据库
//            orderItemMapper.insert(orderItem);
//            //5.删除对应的购物车中的商品,添加完后删除
//            redisTemplate.boundHashOps("cart_" + username).delete(id);
//        }
//        //7.将订单信息发送到mq的延时队列
//        rabbitTemplate.convertAndSend("ttlOrderExchange", "ttl_order", order.getNo());
//        //8.调用支付方法
//        PayObject payObject = new PayObject();
//        payObject.setOutTradeNo(order.getNo());
//        payObject.setTotalAmount(order.getTotalAmount() + "");
//        String form = (String) alipayFeignClient.toPay(payObject).getData();
//
//        return form;
//    }
}
